(function ($) {
    "use strict";
    var Captcha = function (element) {
        var $self = $(element),
            $input = $('input', $self),
            $image_div = $('.captcha-image', $self),
            $link = $('.captcha-refresher', $self),
            $img = $('img[id*=captcha]', $image_div);

        $input.outerWidth($self.width() - $image_div.width() - 10);
        $link.click(function (e) {
            e.preventDefault();
            $img.animate({opacity: 0}, 200, function () {
                $img.attr('src', $link.attr('href') + '?random=' + Math.random())
                .animate({opacity: 1}, 1200);
            });
        });

        if ($.fn.validate_on_keyup) {
            $input.validate_on_keyup(/^.{4}$/, "");
        }
    };

    // Setup captcha
    $.fn.captcha_group = function () {
        return this.each(function () {
            var self = $(this);
            if (!self.data('captcha-group')) {
                self.data('captcha-group', new Captcha(self));
            }
        });
    };


    // Initial Captcha group
    $(function () {
        $('.control-group.captcha').captcha_group();
    });
}(window.jQuery));
